package ctrls;

import ejb.GererConnectLocal;
import entities.Clients;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import javax.ejb.EJB;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author CDI215
 */
public class Ctrl extends HttpServlet {

    @EJB
    private GererConnectLocal gererConnect;
    public static final String ATT_CLIENT = "client";
    private HashMap<String, ISsCtrl> mesCtlrs;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        mesCtlrs = new HashMap();
        for (Enumeration<String> e = config.getInitParameterNames(); e.hasMoreElements();) {
            String name = e.nextElement();
            String valeur = config.getInitParameter(name);

            try {
                ISsCtrl sousCrtl = (ISsCtrl) Class.forName(valeur).newInstance();
                mesCtlrs.put(name, sousCrtl);
            } catch (InstantiationException ex) {
                //Logger.getLogger(Controle.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            } catch (IllegalAccessException ex) {
                //Logger.getLogger(Controle.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            } catch (ClassNotFoundException ex) {
                //Logger.getLogger(Controle.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            }
        }
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        Cookie cookiePresent = getCookie(request, ATT_CLIENT);

        if (cookiePresent != null) {
            Clients client = gererConnect.autoConnect(Long.parseLong(cookiePresent.getValue()));
            session.setAttribute(ATT_CLIENT, client);
        }

        String url = "/WEB-INF/home.jsp";
        String section = request.getParameter("section");

        if (section != null) {
            if (mesCtlrs.containsKey(section)) {
                ISsCtrl sousCtrl = mesCtlrs.get(section);
                url = sousCtrl.execute(request, response);
            }
        }
        getServletContext().getRequestDispatcher(url).forward(request, response);

    }

    private static Cookie getCookie(HttpServletRequest request, String nom) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie != null && nom.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
